<template>
	<view class="workbench-detail">
		<!-- 事项明细标题 -->
		<view class="detail-title">{{ doWorkInfo.items }}</view>
		<!-- 明细概况 -->
		<view class="detail-content">
			<!-- <van-cell title="所属类型" value="售后部" icon="apps-o" /> -->
			<van-cell title="事项分类" :value="doWorkInfo.class" icon="points" />
			<van-cell title="执行标准" :value="doWorkInfo.standard" icon="guide-o" />
		</view>

		<!-- 是否完成 -->
		<view class="detail-iscompleted">
			<view class="detail-completed-form">
				<view class="detail-completed-title">
					<van-icon class="passed-icon" name="passed" />
					<text class="completed-title-text">完成状态</text>
				</view>
				<view class="detail-completed-radio-group">
					<uni-data-checkbox v-model="isCompleted" :localdata="completed" />
				</view>
			</view>
		</view>
		<!-- 点检痕迹 -->
		<view class="detail-tally-trace">
			<view class="detail-trace-title"><text style="color: red;">*</text>执行痕迹</view>
			<view class="detail-tally-imgs">
				<view class="grid-item-box" v-for="(item, index) in imgs" :key="index"
					@tap.stop="ViewImage(item.imgName)">
					<image :src="item.imgName" class="tally-img" mode="aspectFill" />
					<van-icon class="delete-icon" name="clear" @tap.stop="DelImg(index)" />
				</view>
				<view class="grid-item-box detail-tally-img-add" v-show="isAddImgShow" @tap.stop="ChooseImage">
					<van-icon class="add-icon" name="plus" />
				</view>
			</view>
		</view>
		<!-- 痕迹视频 -->
		<view class="detail-tally-trace">
			<view class="detail-trace-title">视频上传</view>
			<view class="detail-tally-imgs">
				<view class="grid-item-box" v-for="(item, index) in videos" :key="index">
					<image :src="item.cover" class="tally-img" mode="aspectFill" />
					<!-- <video class="tally-img" :src="item.imgName"></video> -->
					<view class="play-icon-bg" @tap.stop.prevent="playVideo(item)">
						<van-icon class="play-icon" name="play-circle-o" />
					</view>
					<van-icon class="delete-icon" name="clear" @tap.stop="DelVideo(index)" />
				</view>
				<view class="grid-item-box detail-tally-img-add" v-show="isAddVideoShow" @tap.stop="ChooseVideo">
					<van-icon class="add-icon" name="plus" />
				</view>
			</view>
		</view>
		<!-- 备注 -->
		<view class="detail-tally-trace" v-if="isCompleted == 0">
			<view class="detail-trace-title">备注</view>
			<view class="detail-remark">
				<uni-easyinput type="textarea" :trim="true" :inputBorder="false" v-model="remark" placeholder="请输入备注" />
			</view>
		</view>


		<!-- 是否完成popup -->
		<van-popup :show="completedPopShow" position="bottom">
			<van-picker show-toolbar :columns="completedList" @confirm="onCompletedConfirm"
				@cancel="completedPopShow = false" />
		</van-popup>

		<button class="submit-btn" v-if="submitBtnState" @click.stop.prevent="handleSubmit">确认提交</button>
		<button class="unsubmit-btn" v-else>确认提交</button>
		<view class="height"></view>
	</view>
</template>

<script>
	import apiRqs from "@/api/api-request.js";
	import debounce from "../../common/debounce.js";
	export default {
		data() {
			return {
				remark: '',
				isCompleted: -1,
				completedPopShow: false,
				completedList: ['已完成', '未完成'],
				completed: [{
					text: '已完成',
					value: 1
				}, {
					text: '未完成',
					value: 0
				}],
				doWorkInfo: {},
				imgs: [],
				isAddImgShow: true,
				videos: [],
				isAddVideoShow: true,
				submitBtnState: true,
			}
		},
		onShow() {
			const doWorkInfo = uni.getStorageSync("doWorkInfo");
			if (doWorkInfo) {
				this.doWorkInfo = doWorkInfo;
			}
		},
		methods: {
			handleCompletedPopShow() {
				this.completedPopShow = true;
			},
			onCompletedConfirm(value) {
				this.isCompleted = value.detail.value;
				this.completedPopShow = false;
			},
			// 上传图片
			ChooseImage(index) {
				let imgs = this.imgs;
				let loginInfo = uni.getStorageSync("loginInfo");
				var that = this;
				uni.chooseImage({
					count: 6, //默认最多上传6张图片
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera', 'album'], //从相册选择
					success: (res) => {
						const tempFilePaths = res.tempFilePaths;
						// 将上传的图片分别请求上传到服务器
						if ((imgs.length + tempFilePaths.length) < 9) {
							that.isAddImgShow = true;
						} else if ((imgs.length + tempFilePaths.length) == 9) {
							that.isAddImgShow = false;
						} else {
							that.isAddImgShow = false;
						}
						for (let i = 0; i < tempFilePaths.length; i++) {
							getApp().showLoading();
							uni.uploadFile({
								url: getApp().globalData.websiteUrl + "/api/v1/FileUpload",
								filePath: tempFilePaths[i],
								name: 'file',
								header: {
									'Authorization': ('Bearer ' + loginInfo.token) || ''
								},
								formData: {
									'fileType': 'CheckImg'
								},
								success: (uploadFileRes) => {
									let res = JSON.parse(uploadFileRes.data);
									let filePath = res.data[0].filePath;
									let newFilePath = filePath.replace(/\\/g, "/");
									let d = {
										id: "0",
										checkDetailId: "0",
										imgName: `${getApp().globalData.websiteUrl}${newFilePath}/${res.data[0].fileName}`,
										cover: "",
										width: res.data[0].width,
										height: res.data[0].height,
										softDelete: false
									}
									console.log('imgFileData', d);
									imgs.push(d);
								}
							});
						}
						that.imgs = imgs;

						uni.hideLoading();
					}
				});
			},
			// 预览图片
			ViewImage(imgName) {
				console.log('点击了预览');
				let imgs = this.imgs;
				var dataArray = [];
				for (var i = 0; i < imgs.length; i++) {
					dataArray[i] = imgs[i].imgName;
				}
				uni.previewImage({
					urls: dataArray,
					current: imgName
				});
			},
			// 删除图片
			DelImg(index) {
				this.imgs.splice(index, 1);
				if (this.imgs.length < 9) {
					this.isAddImgShow = true;
				} else if (this.imgs.length == 9) {
					this.isAddImgShow = false;
				} else {
					this.isAddImgShow = false;
				}
			},
			// 上传视频
			ChooseVideo() {
				let loginInfo = uni.getStorageSync("loginInfo");
				var that = this;
				uni.chooseMedia({
					count: 1,
					mediaType: ['video'],
					sourceType: ['camera', 'album'],
					maxDuration: 999,
					compressed: true,
					success: function(res) {
						let videoRes = res.tempFiles[0];
						console.log('视频', res);
						let videoW = res.tempFiles[0].width;
						let videoH = res.tempFiles[0].height;
						if (videoRes.duration > 999) {
							getApp().showToast("视频时长不得大于999秒!");
							return false;
						} else if ((videoRes.size / 1024 / 1024) > 100) {
							getApp().showToast("视频大小不得大于100M!");
							return false;
						} else {
							getApp().showLoading();
							let thumbTempFilePath = videoRes.thumbTempFilePath;
							if (videoRes.tempFilePath) {
								let p1 = new Promise((resolve) => {
									uni.uploadFile({
										url: getApp().globalData.websiteUrl +
											"/api/v1/FileUpload",
										filePath: thumbTempFilePath,
										name: 'file',
										header: {
											'Authorization': ('Bearer ' + loginInfo.token) ||
												''
										},
										formData: {
											'fileType': 'CheckImg'
										},
										success: (uploadFileRes) => {

											let res = JSON.parse(uploadFileRes.data);
											let filePath = res.data[0].filePath;
											let newFilePath = filePath.replace(/\\/g, "/");
											let imgName =
												`${getApp().globalData.websiteUrl}${newFilePath}/${res.data[0].fileName}`;
											resolve(imgName);
										}
									});
								})
								p1.then((img) => {
									console.log('封面图地址', img);
									uni.uploadFile({
										url: getApp().globalData.websiteUrl +
											"/api/v1/FileUpload",
										filePath: videoRes.tempFilePath,
										name: 'file',
										header: {
											'Authorization': ('Bearer ' + loginInfo.token) ||
												''
										},
										formData: {
											'fileType': 'CheckVideo'
										},
										success: (uploadFileRes) => {
											uni.hideLoading();
											let res = JSON.parse(uploadFileRes.data);
											console.log('上传视频地址', res);
											let filePath = res.data[0].filePath;
											let newFilePath = filePath.replace(/\\/g, "/");
											let d = {
												id: "0",
												checkDetailId: "0",
												imgName: `${getApp().globalData.websiteUrl}${newFilePath}/${res.data[0].fileName}`,
												cover: img,
												width: videoW,
												height: videoH,
												softDelete: false
											}
											that.videos.push(d);
										}
									});
								})

								that.isAddVideoShow = false;
							} else {
								uni.hideLoading();
							}
						}

					}
				})
			},
			// 删除视频
			DelVideo(index) {
				this.videos.splice(index, 1);
				this.isAddVideoShow = true;
			},
			// 播放视频
			playVideo(item) {
				wx.previewMedia({
					sources: [{
						url: item.imgName,
						type: "video",
						poster: item.imgSrc
					}]
				})
			},
			handleSubmit() {
				let {
					doWorkInfo,
					imgs,
					videos,
					isCompleted
				} = this;
				if (isCompleted == -1) {
					getApp().showToast("请勾选完成状态");
				} else if (isCompleted == 1 && imgs.length == 0 && videos.length == 0) {
					getApp().showToast("请上传执行痕迹");
				} else {

					// 订阅消息
					var that = this;
					const tokenInfo = uni.getStorageSync("tokenInfo");
					const loginInfo = uni.getStorageSync("loginInfo");
					wx.getSetting({
						withSubscriptions: true,
						success: function(res) {
							console.log('订阅消息', res);
							if (res.subscriptionsSetting.mainSwitch) {
								if (res.subscriptionsSetting.itemSettings && res.subscriptionsSetting
									.itemSettings != 'undefined') { // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权 
									let moIdState = res.subscriptionsSetting.itemSettings && res
										.subscriptionsSetting.itemSettings[
											'DFpqPMWb6mVkInRoCWTz73kbITB9KHVP_KDxwwafbEc'];
									// 用户同意的消息模板id
									if (moIdState === 'accept') {
										that.submitBtnState = false;
										that.requestSubscribeMessage();
									} else if (moIdState === 'reject') {
										uni.showModal({
											title: "提示",
											content: "检测到您没有开启订阅消息的权限，将收不到任务提醒，是否去设置？",
											success(res) {
												if (res.confirm) {
													uni.openSetting();
												} else {
													that.submitDetailRqs();
												}
											}
										})
									} else if (moIdState === 'ban') {} else {}
								} else {
									that.submitBtnState = false;
									that.requestSubscribeMessage();
								}
							} else {
								uni.showModal({
									title: "提示",
									content: "检测到您没有开启订阅消息的权限，将收不到任务提醒，是否去设置？",
									success(res) {
										if (res.confirm) {
											uni.openSetting();
										} else {
											that.submitDetailRqs();
										}
									}
								})
							}
						},
						fail: function(error) {
							console.log(error, "errror+++++++++++")
						}
					})
				}
			},
			//监听用户点击了允许还是拒绝
			requestSubscribeMessage() {
				var that = this;
				const tokenInfo = uni.getStorageSync("tokenInfo");
				const loginInfo = uni.getStorageSync("loginInfo");
				wx.requestSubscribeMessage({
					tmplIds: ['DFpqPMWb6mVkInRoCWTz73kbITB9KHVP_KDxwwafbEc'],
					success(res) {
						console.log('用户点击了允许', res);
						if (res.errMsg == 'requestSubscribeMessage:ok') {
							if (res['DFpqPMWb6mVkInRoCWTz73kbITB9KHVP_KDxwwafbEc'] == 'accept') {
								// console.log("接受了不再询问")
								getApp().showLoading();
								let p1 = new Promise((resolve) => {
									let rqs = {
										"openId": loginInfo.openid,
										"shopId": tokenInfo.shopId
									};
									apiRqs._sendSubcribeMessage(rqs).then((res) => {
										console.log('接口地址：/WxOpen/Add/SubscribeMessage，传输字段：', rqs,
											'最终结果', res);
										resolve();
									}).catch((err) => {
										console.log('err', err);
									})
								})
								p1.then(() => {
									that.submitDetailRqs();
								})
							} else if (res['DFpqPMWb6mVkInRoCWTz73kbITB9KHVP_KDxwwafbEc'] == 'reject') {
								// console.log("用户拒绝了订阅消息")
								getApp().showToast("取消订阅消息将无法收到工作任务提醒");
								setTimeout(() => {
									that.submitDetailRqs();
								}, 1500)
							}
						} else {
							getApp().showToast('fail');
						}
					}
				})
			},
			submitDetailRqs() {
				let {
					doWorkInfo,
					imgs,
					videos,
					isCompleted
				} = this;
				let newMediaFiles = JSON.parse(JSON.stringify(imgs));
				if (videos.length > 0) {
					newMediaFiles.push({
						"id": videos[0].id,
						"checkDetailId": videos[0].checkDetailId,
						"imgName": videos[0].imgName,
						"cover": videos[0].cover,
						"width": videos[0].width,
						"height": videos[0].height,
						"softDelete": false
					})
				}
				let checkObject = doWorkInfo.checkObject + '';
				getApp().showLoading();
				let rqs = {
					"checkId": doWorkInfo.checkId,
					"tempId": doWorkInfo.tempId,
					"class": doWorkInfo.class,
					"items": doWorkInfo.items,
					"standard": doWorkInfo.standard,
					"frequency": doWorkInfo.frequency,
					"result": isCompleted,
					"checkObject": checkObject,
					"checkPost": doWorkInfo.checkPost,
					"imgs": newMediaFiles,
					"remark": isCompleted == 0 ? this.remark : "",
				};
				console.log('提交点检请求rqs', rqs);
				apiRqs._submitWork(rqs).then((res) => {
					console.log('提交结果', res);
					uni.hideLoading();
					if (res.code == 200) {
						getApp().showToast("提交成功", "success");
						setTimeout(() => {
							uni.navigateBack();
						}, 1500)
					} else {
						getApp().showToast(res.msg);
					}
				}).catch((err) => {
					console.log('err', err);
				})
			},
		},
	}
</script>

<style lang="less">
	page {
		background-color: #f5f5f5;
	}

	.workbench-detail {
		.height {
			height: 40px;
		}

		.detail-title {
			background-color: #fff;
			padding: 16px 17px;
			font-size: 16px;
			color: #000;
		}

		.detail-content {
			margin-top: 10px;

			.van-cell {
				padding-top: 16px;
				padding-bottom: 16px;
			}

			.van-icon {
				color: #008aff;
			}
		}

		.detail-tally-trace {
			margin-top: 10px;

			.detail-trace-title {
				font-size: 12px;
				color: #999999;
				margin-left: 16px;
			}

			.detail-tally-imgs {
				background-color: #fff;
				margin-top: 10px;
				padding: 0px 15px 15px 15px;
				box-sizing: border-box;
				display: flex;
				flex-wrap: wrap;

				.grid-item-box {
					width: 100px;
					height: 100px;
					position: relative;
					margin-left: 15px;
					margin-top: 15px;

					&:nth-child(3n+1) {
						margin-left: 0;
					}

					.tally-img {
						width: 100%;
						height: 100%;
					}

					.play-icon-bg {
						position: absolute;
						top: 0;
						left: 0;
						width: 100%;
						height: 100%;
						background-color: rgba(0, 0, 0, 0.3);
						z-index: 20;

						.play-icon {
							position: absolute;
							top: 50%;
							left: 50%;
							font-size: 30px;
							color: #fff;
							margin-left: -15px;
							margin-top: -15px;
						}
					}

					.delete-icon {
						position: absolute;
						top: -10px;
						right: -10px;
						color: #FF1010;
						background-color: #fff;
						font-size: 22px;
						border-radius: 50%;
						z-index: 99;
					}

					&.detail-tally-img-add {
						text-align: center;
						line-height: 100px;
						border: 1px solid #efefef;
						box-sizing: border-box;

						.add-icon {
							font-size: 28px;
							color: #999999;
						}
					}
				}
			}

			.detail-remark {
				margin-top: 10px;
				background-color: #fff;
				padding: 10px 16px;
				box-sizing: border-box;
			}
		}

		.detail-iscompleted {
			background-color: #fff;

			.detail-completed-form {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 16px 0px 16px 17px;

				.detail-completed-title {
					display: flex;
					align-items: center;

					.passed-icon {
						font-size: 16px;
						color: #008aff;
					}

					.completed-title-text {
						font-size: 14px;
						color: #333;
						margin-left: 5px;
					}
				}

				.detail-completed-radio-group {}
			}
		}

		.submit-btn {
			margin: 20px 15px;
			border: none;
			background-color: #008aff;
			color: #fff;
			font-size: 15px;
			height: 35pt;
			line-height: 35pt;

			&:active {
				background-color: #0076DB;
			}

		}

		.unsubmit-btn {
			margin: 20px 15px;
			border: none;
			background-color: #ccc;
			color: #fff;
			font-size: 15px;
			height: 35pt;
			line-height: 35pt;

			&::after {
				border: none;
			}
		}
	}
</style>
